<script setup lang="ts">
import CommentBox from "./commentBox/index.vue"
import CommentList from "./commentList/index.vue"
import {onBeforeMount, ref, watch, computed} from "vue";
import {addComment, getCommentList} from "@/api/comment/comment";
import {EAction, ECode} from "@/util/commonUtil";
import {message} from "ant-design-vue";
import {useSysEventStore} from "@/store/system/SysEventStore";
import {Empty} from 'ant-design-vue';
import {v4 as uuidV4} from 'uuid';
import {useAppConfigStore} from "@/store/system/appConfigStore";

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
const props = defineProps({
  targetId: [Number, String],
  tableName: {
    type: String,
    default: '',
  },
  // 控制最大评论层级
  maxReplyLevel: {
    type: Number,
    default: 5,
  },
  // 左边偏移量
  marginLeft: {
    type: Number,
    default: -3,
  },
  // 作者UID
  authorUid: {
    type: String,
    default: '',
  },
  // 是否显示取消按钮
  showCancel: {
    type: Boolean,
    default: true
  },
  // 是否显示评论框
  showCommentBox: {
    type: Boolean,
    default: false
  }
});

onBeforeMount(() => {
  getCommentDataList()
})

const comments = ref<any>([])
const isEnd = ref<boolean>(false)
const commentInfo = ref<any>({
  blogUid: props.targetId,
  source: props.tableName
})
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)
const commentFinish = ref<boolean>(false)
const componentShowMap = computed(() => useAppConfigStore().componentShowMap)

watch(() => props.targetId, (newValue) => {
  commentInfo.value.blogUid = newValue;
  getCommentDataList()
})
watch(() => useSysEventStore().commentMessage, () => {
  getCommentDataList()
})

function submitBox(e: any) {
  let params: any = {};
  params.source = e.source;
  params.userUid = e.userUid;
  params.content = e.content;
  params.blogUid = e.blogUid;
  addComment(params).then((response: any) => {
    if (response.code === ECode.SUCCESS) {
      if (response.data.auditStatus === "2") {
        commentFinish.value = true
        message.success("评论成功！");
        useSysEventStore().setCommentMessage(uuidV4())
      } else {
        commentFinish.value = true
        message.warning("提交成功，请耐心等待审核~");
      }
      let commentData = response.data
      comments.value.unshift(commentData)
      isEnd.value = false
      // 发送评论的领域事件
      let event = {
        "type": "action",
        "action": EAction.Comment,
        "resourceUid": e.blogUid,
        "resourceType": "BLOG",
        "time": new Date(),
      }
      useSysEventStore().setDomainEventMessage(event)
    } else {
      message.error(response.message)
    }
  })
}

function getCommentDataList() {
  let source = commentInfo.value.source
  let blogUid = commentInfo.value.blogUid
  let sourceList = ["BLOG_INFO", "PROBLEM_INFO", "QUESTION_INFO", "MEDIA_INFO"]
  if (sourceList.includes(source) && !blogUid) {
    return
  }
  let params: any = {};
  params.source = commentInfo.value.source;
  params.blogUid = commentInfo.value.blogUid;
  params.currentPage = currentPage.value;
  params.pageSize = pageSize.value;
  params.openSecondLevel = true;
  getCommentList(params).then((response: any) => {
    if (response.code === ECode.SUCCESS) {
      let newDataList = response.data.records
      comments.value = response.data.records;
      currentPage.value = response.data.current;
      pageSize.value = response.data.size;
      total.value = response.data.total
      if (newDataList.length < pageSize.value) {
        isEnd.value = true;
      }
      if (comments.value.length === total.value) {
        isEnd.value = true;
      }
    }
  });
}

function loadMore() {
  let params: any = {};
  params.source = commentInfo.value.source;
  params.blogUid = commentInfo.value.blogUid;
  params.currentPage = currentPage.value + 1
  params.pageSize = pageSize.value;
  params.openSecondLevel = true;
  getCommentList(params).then((response: any) => {
    if (response.code === ECode.SUCCESS && response.data.records.length > 0) {
      let newDataList = response.data.records
      comments.value = comments.value.concat(response.data.records);
      useSysEventStore().setCommentList(comments.value);
      currentPage.value = response.data.current;
      pageSize.value = response.data.size;
      total.value = response.data.total;
      //全部加载完毕
      if (newDataList.length < pageSize.value) {
        isEnd.value = true;
      }
      if (comments.value.length === total.value) {
        isEnd.value = true;
      }
    } else {
      isEnd.value = true;
    }
  })
}
</script>

<template>
  <main class="commentMain overflow-hidden" id="comment">
    <CommentBox v-if="componentShowMap.showUserComment"
                :commentInfo="commentInfo"
                @submit-box="submitBox"
                :commentFinish="commentFinish"
                :showCancel="showCancel"
                :class="showCommentBox ? 'hidden':''"/>
    <!--评论列表-->
    <section class="commentList">
      <CommentList :tableName="tableName"
                   :comments="comments"
                   :authorUid="authorUid"
                   :marginLeft="marginLeft"
                   :commentInfo="commentInfo"
                   :maxReplyLevel="maxReplyLevel">
        <template #header-right>
          <slot/>
        </template>
      </CommentList>
    </section>
    <!-- 加载更多 -->
    <section class="commentMore w-full flex justify-center mt-4">
      <a-empty :image="simpleImage" v-if="comments.length == 0 && isEnd"/>
      <a-button type="default" v-if="!isEnd" @click="loadMore">加载更多</a-button>
      <span v-if="isEnd && comments.length > 0" class="text-gray-400">我也是有底线的~</span>
    </section>
  </main>
</template>

<style scoped lang="less">
@media (max-width: 1024px) {
  .commentMain{
    padding-inline: var(--edge-lr);
  }
}
</style>
